package com.changjie.wang.doc;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;

import javax.swing.text.Highlighter;
import java.io.IOException;

public class EsClient_QueryDoc {
    /**
     * ES高级查询文档数据-聚合查询
     * @param args
     */
    public static void main(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            //聚合查询
            SearchRequest request = new SearchRequest();
            request.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder();
            //取年龄最大的
            AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
            builder.aggregation(aggregationBuilder);
//            //分组查询
//            AggregationBuilder aggregationBuilder1 = AggregationBuilders.terms("ageGroup").field("age");
//            builder.aggregation(aggregationBuilder1);
            
            request.source(builder);
            SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());

            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * ES高级查询文档数据-模糊查询 & 高亮显示
     * @param args
     */
    public static void fuzzyQuery(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            //模糊查询
            SearchRequest request = new SearchRequest();
            request.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder().query(
                    QueryBuilders.fuzzyQuery("name","刘"));

            //定义高亮显示规则
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.preTags("<font color='red'>");
            highlightBuilder.postTags("</font>");
            builder.highlighter(highlightBuilder);

            request.source(builder);
            SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());

            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * ES高级查询文档数据-范围查询
     * @param args
     */
    public static void rangeQuery(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            //范围查询
            SearchRequest request = new SearchRequest();
            request.indices("user");
            //查询大于50岁，小于60岁的user
            SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.rangeQuery("age").gte(50).lt(60));

            request.source(builder);
            SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());

            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * ES高级查询文档数据-排序查询
     * @param args
     */
    public static void sortQuery(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            //查询排序
            SearchRequest request = new SearchRequest();
            request.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
            //规定排序规则，此处为降序查询
            builder.sort("age", SortOrder.DESC);

            //可以规定查询哪些字段，不查询哪些字段
            String[] excludes = {};
            String[] includes = {"name"};
            //注意入参顺序，第一个是需要查询，第二个是不需要查询
            builder.fetchSource(includes,excludes);

            request.source(builder);
            SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());

            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ES高级查询文档数据-分页查询
     * @param args
     */
    public static void pagingQuery(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            //分页查询
            SearchRequest request = new SearchRequest();
            request.indices("user");
            SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
            //规定从哪开始
            builder.from(0);
            //规定显示几条
            builder.size(3);
            request.source(builder);
            SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());

            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ES高级查询文档数据-条件查询
     * @param args
     */
    public static void conditionQuery(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            SearchRequest request = new SearchRequest();
            request.indices("user");
//            //表示查询年龄为60的user
//            request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",60)));

            //多条件查询and
            request.source(new SearchSourceBuilder().query(QueryBuilders.boolQuery().
                    must(QueryBuilders.matchQuery("age","60")).
                    must(QueryBuilders.matchQuery("name","刘德华"))));
            //多条件查询or
            request.source(new SearchSourceBuilder().query(QueryBuilders.boolQuery().
                    should(QueryBuilders.matchQuery("age","60")).
                    should(QueryBuilders.matchQuery("name","刘德华"))));
            SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());

            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ES高级查询文档数据-全量查询
     * @param args
     */
    public static void fullQuery(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            SearchRequest request = new SearchRequest();
            request.indices("user");
            request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));

            SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());

            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
